package juc;

import lombok.extern.slf4j.Slf4j;


//基于test03的基础上，将锁的职责独立成对象
@Slf4j(topic = "c.Test03Plus01")
public class Test03Plus01 {
    static Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
        Room room = new Room();

        Thread t1 = new Thread(() -> {
            for(int i=0;i<5000;i++){
                room.increment();
                log.debug("t1的第{}次++",i);
            }
        },"t1");
//        LockSupport.park(t1);
        Thread t2 = new Thread(() -> {
            for(int i=0;i<5000;i++){
                room.decrement();
                log.debug("t2的第{}次--",i);
            }
        },"t2");

        t1.start();
        t2.start();
        //这里需要加入join,需要等t1和t2一起结束，才能打印出来a
        t1.join();
        t2.join();

        log.debug("a的值为：{}",room.getCounter());
    }

}

// 该类充当锁的职责
class Room{
    private int counter = 0;

    //这种写法，和下面的写法作用一样
    public synchronized void increment(){
        counter++;
    }

    public void decrement(){
        synchronized(this){
            counter--;
        }
    }

    public int getCounter(){
        synchronized (this){
            return counter;
        }
    }
}
